//
//  ViewController.m
//  BlurOC
//
//  Created by sun on 16/3/30.
//  Copyright © 2016年 sun. All rights reserved.
//

#import "ViewController.h"
#import "UIImageEffects.h"
#import "UIImage+ImageEffects.h"
#import "BlurredUILabel.h"
#import "UIView+Effects.h"
#import "FXBlurView.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()

@property (nonatomic, copy) NSString *text;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, weak) UILabel *label;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) AVAudioPlayer *player;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.text = @"hello, sunfei.";
    
//    self.view.backgroundColor = [UIColor greenColor];
    
    [self secondBlur];
    
    FXBlurView *blurView = [[FXBlurView alloc] init];
    blurView.backgroundColor = [UIColor whiteColor];
    blurView.tintColor = [UIColor clearColor];
    blurView.frame = self.view.bounds;
    blurView.blurRadius = 4;
    blurView.dynamic =YES;
    [self.view addSubview:blurView];
    
    // 下载音频
    [self download];
}

- (void)firstBlur {
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 1);
    [self.text drawInRect:self.view.bounds withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20], NSForegroundColorAttributeName:[UIColor redColor]}];
    //    [self.text drawAtPoint:CGPointMake(0, 0) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12], NSForegroundColorAttributeName:[UIColor redColor]}];
    self.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    self.imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.imageView];
    self.imageView.image = self.image.applyLightEffect;
}

- (void)secondBlur {
    UILabel *label = [[UILabel alloc] initWithFrame:self.view.bounds];
    label.font = [UIFont systemFontOfSize:25.0f];
    label.text = self.text;
    label.numberOfLines = 0;
    [self.view addSubview:label];
    self.label = label;
    
//    [self updateBlur];
}

- (void)thirdBlur {
    self.image = [UIImage imageNamed:@"contactsNight"];
//    UIGraphicsBeginImageContextWithOptions(self.image.size, NO, self.image.scale);
////    [self.image drawAtPoint:CGPointZero];
//    [self.text drawInRect:self.view.bounds withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12], NSForegroundColorAttributeName:[UIColor redColor]}];
//    self.image = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
    UIImage *effectImage = self.image.applyLightEffect;
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, self.image.size.width, self.image.size.height)];
    [self.view addSubview:self.imageView];
    self.imageView.image = effectImage;
}

- (void)fourBlur {
//    UILabel*label = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 300, 100)];
    BlurredUILabel *label = [[BlurredUILabel alloc] initWithFrame:CGRectMake(50, 50, 300, 100)];
    label.blurRadius = 5.5;
    label.backgroundColor = [UIColor redColor];
//    label.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:35];
    label.font = [UIFont systemFontOfSize:20];
//    [label sizeToFit];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"HELLO";
    [self.view addSubview:label];
    
    label.blurRadius = 1;
    [label performSelector:@selector(setText:) withObject:@"HELLO" afterDelay:2];
}

- (void)fiveBlur {
    [self secondBlur];
    // Create the image context
    UIGraphicsBeginImageContextWithOptions(self.label.bounds.size, YES, 1);
    
    // There he is! The new API method
    [self.label drawViewHierarchyInRect:self.label.bounds afterScreenUpdates:YES];
    
    // Get the snapshot
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // Now apply the blur effect using Apple's UIImageEffect category
    UIImage *blurredSnapshotImage = [snapshotImage applyLightEffect];
    
    // Or apply any other effects available in "UIImage+ImageEffects.h"
    // UIImage *blurredSnapshotImage = [snapshotImage applyDarkEffect];
    // UIImage *blurredSnapshotImage = [snapshotImage applyExtraLightEffect];
    
    // Be nice and clean your mess up
    UIGraphicsEndImageContext();
    [self showImage:blurredSnapshotImage];
   
}

- (void)showImage:(UIImage *)image {
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    [self.view addSubview:self.imageView];
    self.imageView.image = image;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)updateBlur {

//    UIGraphicsBeginImageContext(self.view.bounds.size);
//    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
//    
//    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
//    
//    UIGraphicsEndImageContext();
////    self.label.hidden = YES;
////    UIImage *blur = [UIImageEffects imageByApplyingExtraLightEffectToImage:viewImage];
//    UIImage *blur = [viewImage applyExtraLightEffect];
//    self.imageView.image = blur;
    
    UIGraphicsBeginImageContextWithOptions(self.label.bounds.size, NO, 0);
//    [self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];
    [self.label.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImage *blur = screenshot.applyLightEffect;
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:blur];
    [imageView sizeToFit];
    [self.view addSubview:imageView];
}

- (void)applyBlur
{
    UIImage *screen = [self captureScreenInRect:self.view.bounds];
    UIImage *blur = [screen applyDarkEffect];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.frame];
    imageView.image = blur;
    [self.view addSubview:imageView];
}

- (UIImage *)captureScreenInRect:(CGRect)captureFrame
{
    [self secondBlur];
    CALayer *layer;
    layer = self.label.layer;
    UIGraphicsBeginImageContext(self.label.bounds.size);
    CGContextClipToRect (UIGraphicsGetCurrentContext(),captureFrame);
    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenImage;
}

- (NSString *)pathToSave {
    NSString *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    return filePath;
}

- (void)download {
    // 创建请求
    NSURLSessionConfiguration *configure = [NSURLSessionConfiguration defaultSessionConfiguration];
    [configure setTimeoutIntervalForRequest:20];
    [configure setTimeoutIntervalForResource:20];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configure];
    // 开始请求
    [[session downloadTaskWithURL:[NSURL URLWithString:@"http://openmp3.ezjie.com/oldtpo/20151027/778eed2636e2cccb031ab56f922bb169.mp3"] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 得到下载的数据
        NSData *data = [NSData dataWithContentsOfURL:location];
        // 将数据保存到用户目录中
        if ([data writeToFile:[[self pathToSave] stringByAppendingPathComponent:@"sunfei.mp3"]
                   atomically:NO]) {
            NSLog(@"success");
        } else {
            NSLog(@"failed");
        }
        // 播放音频
        dispatch_async(dispatch_get_main_queue(), ^{
            NSError *audioError = nil;
            AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error:&audioError];
            player.volume = 1.0f;
            [player prepareToPlay];
            [player play];
            self.player = player;
        });
        
    }] resume];
}

@end
